/* 
 * File:   File.cpp
 * Author: Guilherme Monteiro
 * 
 */

#include "../headers/File.h"

File::File(string p) throw (InvalidFileException) {
    setPath(p);
}

File::File(const File& orig) {
}

File::~File() {
}

/**
 * Open the file in ios::app mode.
 */
void File::open() throw (InvalidFileException) {
    try {
        file.open(path.c_str(), ios::app | ios::out);
    }
    catch(...) {
        throw InvalidFileException(path);
    }
}

/**
 * Close the file.
 */
void File::close() {
    file.close();
}

/**
 * Open the file with ios::trunc mode and write the header file, at
 * the end close the file.
 * 
 * @param header: corresponds to a signature of a table, with
 * topLeft and rightBottom points.
 * 
 */
void File::writeHeader1(string header) {
    file.open(path.c_str(), ios::trunc | ios::out);
    file << header.append("\n");
    file.close();
}

/**
 * Open the file with ios::app mode and write the header file, at
 * the end close the file.
 * 
 * @param header: corresponds to a signature of a table, with
 * topLeft and rightBottom points.
 * 
 */
void File::writeHeaderN(string header) {
    file.open(path.c_str(), ios::app | ios::out);
    file << header.append("\n");
    file.close();
}

/**
 * Write a line in the file.
 * 
 * @param line
 */
void File::writeLine(string line) throw (InvalidFileException) {
    try {
        file << line.append("\n");
    }
    catch(...) {
        cerr << "Unable to open file. Method: writeLine" << endl;
    }
}

/**
 * Read the set of lines of the file.
 * 
 * @return vector of lines read
 */
vector<string> File::readLines() {
    vector<string> lines;
    try {
        file.open(path.c_str(), ios::in);

        string line;
        if (file.is_open())
        {
          while ( file.good() )
          {
            getline (file, line);
            if(strcmp(line.c_str(), "") != 0)
                lines.push_back(line);
          }
          file.close();
        }
    }
    catch(...) {
        cerr << "Unable to open file. Method: readLines" << endl;
    }
    return lines;
}

/**
 * Sets the path to the file.
 * 
 * @param path
 */
void File::setPath(string path) throw (InvalidFileException) {
    if(path.length() > 0) {
        this->path = path;
    }
    else {
        throw InvalidFileException(path);
    }
}